/*!
 @header OrderConfirmViewController.m
 @author 周益
 @version 1.0.0 2013/02/06 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "OrderPickerViewController.h"
#import "JSONRequest.h"
#import "Config.h"
#import "Helper.h"
#import "JMFBase.h"


//  -----------------------类详细介绍-----------------------
//  根据isDelivery:方法判断此picker完成的是设置配送方式还是收货地址；
//
//  如果是配送方式那么通过上级页面传递过来的NSIndexPath对象，判断是否被用户标记过；
//  如果是选择地址，那么通过consIdSelected即地址的ID来判断是否被用户选择过；
//
//  用户点击后，通过代理，响应到上级页面，显示和标记用户标记过的内容。

//  重点的逻辑是在选择地址时和用户添加了新地址后，选中的标记的切换逻辑。
//
//  <功能描述>：当用户是未选择过选择地址时，即consIdSelected对象为nil，并且存在用户设置的默认地址，那么就标记这个默认地址。
//            当用户以前选择过地址时，即consIdSelected对象不为nil，此时就不管是否有默认地址，就标记地址id为consIdSelected的地址。
//            当用户添加过新地址后，由于在viewWillAppear重新请求了一次地址列表，reload tableview即可。
//
//  -----------------------类升级日志-----------------------
//
//  修改人   修改时间        修改描述              版本
//
// <#修改人#> <#修改时间#>    <#修改描述#>          <#版本#>

@interface OrderPickerViewController ()

@end

@implementation OrderPickerViewController
@synthesize deliveryIsSelected = _deliveryIsSelected;
@synthesize consIdSelected = _consIdSelected;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

/*!
 @abstract 设置用户选择的是配送方式还是地址信息
 @param yesOrNo 为true则表示为配送方式，否则为地址信息。
 */
- (void)isDelivery:(BOOL)yesOrNo
{
    _isDelivery = yesOrNo;
}

/*!
 @abstract 设置用户选择过哪一种配送方式的方法
 @param indexPath 被用户选择的配送方式的indexpath
 */
- (void)setWhichRowIsSelectedForDelivery:(NSIndexPath *)indexPath
{
    _indexPathForDeliveryIsSelected = indexPath;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    //导航按钮左侧：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    //导航栏右侧按钮：添加
    UIButton* addButton = [Helper buttonWithStyle:ButtonStyleNavigationAdd];
    [addButton addTarget:self action:@selector(addConsgineeEvent:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    
    
    //设定两种配送方式
    if (_isDelivery) {
        NSDictionary *way_1 = [NSDictionary dictionaryWithObjectsAndKeys:_L(@"title_method_02"), @"way", _L(@"title_method_detail_01"), @"way_detail", nil];
        NSDictionary *way_2 = [NSDictionary dictionaryWithObjectsAndKeys:_L(@"title_method_03"), @"way", _L(@"title_method_detail_02"), @"way_detail", nil];
        addButton.hidden = YES;
        _dataSource = [NSMutableArray arrayWithObjects:way_1, way_2, nil];
    }
    
    _blankPage = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 832.0f/2.0f)];
    
    self.view.backgroundColor = [UIColor whiteColor];
}
//  视图退出后清空数据，回收资源，因为有可能实例是静态对象
//
- (void)viewDidDisappear:(BOOL)animated
{
//    [self.tableView reloadData];
}


// 视图将要载入时，刷新圈子信息
//
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //如果操作是取收货地址的话，向服务器发送获取收货地址的请求
    if (!_isDelivery) {
        //发出异步请求
        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CONSIGNEE_LIST];
        request.delegate = (id)self;
        request.hudOn = true;
        request.hudTitle = _L(@"title_loading_01");
        [request asynchronous];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    
    //配送方式只有两种
    if (_isDelivery) {
        return 2;
    }else{
        return _dataSource.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        if (_isDelivery) {
            
            //绘制配送方式row
            UILabel *deliveryWay = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 25)];
            deliveryWay.font = _SYS_FONT_005;
            [cell.contentView addSubview:deliveryWay];
            
            UILabel *deliveryDetail = [[UILabel alloc] initWithFrame:CGRectMake(deliveryWay.frame.origin.x + deliveryWay.frame.size.width + 20, 7, 154, 30)];
            deliveryDetail.font = _SYS_FONT_003;
            deliveryDetail.numberOfLines = 0;
            deliveryDetail.textColor = _SYS_COLOR_002;
            [cell.contentView addSubview:deliveryDetail];
        }else{
            
            //绘制收货地址row
            //姓名与地址
            UILabel *nameAndAddressLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 300, 15)];
            nameAndAddressLabel.font = _SYS_FONT_003;
            [cell.contentView addSubview:nameAndAddressLabel];
            
            //详细地址
            UILabel *addressDetailLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, nameAndAddressLabel.frame.origin.y + nameAndAddressLabel.frame.size.height + 5, 300, 15)];
            addressDetailLabel.textColor = _SYS_COLOR_002;
            addressDetailLabel.font = _SYS_FONT_001;
            [cell.contentView addSubview:addressDetailLabel];
            
        }
        
        //绘制“钩钩”标记
        UIImageView* selectorImageView = [[UIImageView alloc] initWithFrame:CGRectMake(300, 15, 14, 14)];
        
        [cell.contentView addSubview:selectorImageView];
        
    }
    
    if (_isDelivery) {
        
        //填充配送方式
        
        UILabel *deliveryWay = [[cell.contentView subviews] objectAtIndex:0];
        UILabel *deliveryDetail = [[cell.contentView subviews] objectAtIndex:1];
        
        NSDictionary *delivery = [_dataSource objectAtIndex:indexPath.row];
        
        //设值
        deliveryWay.text = [delivery objectForKey:@"way"];
        deliveryDetail.text = [delivery objectForKey:@"way_detail"];
        
        if ([deliveryWay.text isEqualToString:_deliveryIsSelected]) {
            
            UIImageView* selectorImageView = [[cell.contentView subviews] objectAtIndex:2];
            [selectorImageView setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_icon_004@2x" ofType:@"png"]]];
        }
        
    }else{
        
        //填充收货地址内容
        UILabel *nameAndAddressLabel = [[cell.contentView subviews] objectAtIndex:0];
        UILabel *addressDetailLabel = [[cell.contentView subviews] objectAtIndex:1];
        UIImageView* selectorImageView = [[cell.contentView subviews] objectAtIndex:2];
        
        //避免用于cell重用，“钩钩”去掉
        selectorImageView.image = nil;

        NSDictionary *receiving = [_dataSource objectAtIndex:indexPath.row];
        nameAndAddressLabel.text = [NSString stringWithFormat:@"%@ %@", [receiving objectForKey:@"consignee"], [receiving objectForKey:@"region"]];
        
        addressDetailLabel.text = [receiving objectForKey:@"address"];        
        
        //当用户未选择地址时，并且此地址是用户设置的默认地址，那么就标记它。
        //当用户选择地址时，标记它。
        if ((_consIdSelected == nil && [[receiving objectForKey:@"status"] integerValue] == 1) || (_consIdSelected != nil && [[receiving objectForKey:@"id"] integerValue] == _consIdSelected.integerValue)) {
            
            [selectorImageView setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_icon_004@2x" ofType:@"png"]]];
            
            
            _consIdSelected = [NSNumber numberWithInt:[[receiving objectForKey:@"id"] integerValue]];
        
        }
    }
    return cell;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    
    int row = [indexPath row];
    
    if (_isDelivery) {
        //设置已勾选
        //先取消以前被勾选的
        
        UITableViewCell *cellIsSelected = [tableView cellForRowAtIndexPath:_indexPathForDeliveryIsSelected];
        
        UIImageView* imageView = [[cellIsSelected.contentView subviews] objectAtIndex:2];
        [imageView setImage:nil];
        
        //设置当前用户点击的
        UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
        UIImageView* selectorImageView = [[cell.contentView subviews] objectAtIndex:2];
        [selectorImageView setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_icon_004@2x" ofType:@"png"]]];
        
        
        //调用代理，让上级view响应用户选择的，并且保存用户在picker页面标记过的
        [_delegate deliveryPicked:[[_dataSource objectAtIndex:row] objectForKey:@"way"] andIndexPath:indexPath];
        _indexPathForDeliveryIsSelected = indexPath;
        
    }else{
        //设置已勾选
        //先取消以前被勾选的
        
        for (int i = 0; i < _dataSource.count; i++) {
            
            NSDictionary *address = [_dataSource objectAtIndex:i];
            
            if (_consIdSelected != nil && [[address objectForKey:@"id"] integerValue] == _consIdSelected.integerValue) {
            
                UITableViewCell *cellIsSelected = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];

                UIImageView* imageView = [[cellIsSelected.contentView subviews] objectAtIndex:2];
                [imageView setImage:nil];
            }
        }
        
        //设置当前用户点击的
        UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
        UIImageView* selectorImageView = [[cell.contentView subviews] objectAtIndex:2];
        [selectorImageView setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_icon_004@2x" ofType:@"png"]]];
        
        //调用代理，让上级view响应用户选择的，并且保存用户在picker页面标记过的
        NSDictionary *receiving = [_dataSource objectAtIndex:indexPath.row];
        
        _consIdSelected = [NSNumber numberWithInt:[[receiving objectForKey:@"id"] integerValue]];
        [_delegate addressPicked:receiving andId:_consIdSelected];
        
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - JSONRequest Delegate
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        //成功的获取了圈子数据后，清除_dataSource的数据。后面会对这个部分重新填充
        //判断一下是否有实例
        if (_dataSource == nil) {
            _dataSource = [[NSMutableArray alloc] init];
        }
        
        if (_dataSource.count != 0) {
            [_dataSource removeAllObjects];
        }
        
        [_dataSource addObjectsFromArray:(NSArray *)jmf.data];
        
        
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
    
    //如果收货地址数为0，则添加新建收货地址
    if (_dataSource.count == 0) {
        
        //空白页处理
        _blankPage.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_img_002@2x" ofType:@"png"]];
        
        [self.view addSubview:_blankPage];
    }
    else{
        
        [_blankPage removeFromSuperview];
    }
    
    [self.tableView reloadData];
}


- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:@"" andMessage:_L(@"title_networkunavailabe")];
}

#pragma mark - 自定义事件

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent
{
    [self.navigationController popViewControllerAnimated:YES];
}

/*!
 @abstract 添加地址按钮事件
 */
- (void)addConsgineeEvent:(id)sender
{
    ConsigneeFormViewController *consigneeFormViewController = [[ConsigneeFormViewController alloc] init];
    consigneeFormViewController.dismissMode = true;
    
    UINavigationController *consigneeFormNavigationController = [[UINavigationController alloc] initWithRootViewController:consigneeFormViewController];
    [Helper navigationControllerCommonStyle:consigneeFormNavigationController];
    
    [self.navigationController presentModalViewController:consigneeFormNavigationController animated:YES];
}

@end
